<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /*
      因为它不一定是正方形，所以循环遍历次数需要找到最小的那条边/2
      */
      var spiralOrder = function (matrix) {
        let m = matrix.length;
        let n = matrix[0].length;
        let mini = Math.min(m, n);
        let loop = parseInt(mini / 2);
        let startX = 0;
        let startY = 0;
        let res = [];
        let offset = 1;
        let i = startX;
        let j = startY;
        while (loop--) {
          i = startX;
          j = startY;
          for (; j < n - offset; j++) {
            res.push(matrix[i][j]);
          }
          for (; i < m - offset; i++) {
            res.push(matrix[i][j]);
          }
          for (; j > startY; j--) {
            res.push(matrix[i][j]);
          }
          for (; i > startX; i--) {
            res.push(matrix[i][j]);
          }
          startX++;
          startY++;
          offset++;
        }
        //如果mini%2!=0 说明中间会留下一行或者一列
        if (mini % 2 != 0) {
          //这时候必须重新赋值
          i = startX;
          j = startY;
          //判断是行还是列
          if (mini == m) {
            //说明是行,这时候把一整行都填进去，注意，这里是左闭右闭了
            for (; j < n - offset + 1; j++) {
              res.push(matrix[i][j]);
            }
          } else {
            //说明是列
            for (; i < m - offset + 1; i++) {
              res.push(matrix[i][j]);
            }
          }
        }
        return res;
      };
      console.log(spiralOrder([[3], [2]]));
    </script>
  </body>
</html>
